//
// Created by korion chen on 6/24/21.
//
#include "com_korion_lame_Mp3Encoder.h"
#include "mp3_encoder.h"
#include "android/log.h"

#define TAG "MP3_LAME"
#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)

#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_korion_lame_Mp3Encoder
 * Method:    init
 * Signature: (Ljava/lang/String;IIILjava/lang/String;)I
 */

Mp3Encoder *encoder;

JNIEXPORT jint JNICALL Java_com_korion_lame_Mp3Encoder_init
        (JNIEnv *env, jclass jclazz,
                jstring pcmFilePath, jint audioChannels, jint bitDepth, jint sampleRate, jstring mp3FilePath){
        LOGI("Java_com_korion_lame_Mp3Encoder_init");
        const char *pcm_file_path = NULL;
        const char *mp3_file_path = NULL;
        pcm_file_path = env->GetStringUTFChars(pcmFilePath, NULL);
        mp3_file_path = env->GetStringUTFChars(mp3FilePath, NULL);

        LOGI("pcm path:%s, mp3 path: %s", pcm_file_path, mp3_file_path);
        encoder = new Mp3Encoder();
        jint result = encoder->Init(pcm_file_path, mp3_file_path, sampleRate, audioChannels, bitDepth);

        env->ReleaseStringUTFChars(pcmFilePath, pcm_file_path);
        env->ReleaseStringUTFChars(mp3FilePath, mp3_file_path);

        return result;
}

/*
 * Class:     com_korion_lame_Mp3Encoder
 * Method:    encode
 * Signature: ()V
 */
JNIEXPORT jint JNICALL Java_com_korion_lame_Mp3Encoder_encode
(JNIEnv *env, jclass jclazz){
    LOGI("Java_com_korion_lame_Mp3Encoder_encode");
    if (encoder != NULL) {
        return encoder->Encode();
    } else {
        LOGE("not init encoder.");
        return -1;
    }
}

/*
 * Class:     com_korion_lame_Mp3Encoder
 * Method:    destroy
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_korion_lame_Mp3Encoder_destroy
(JNIEnv *env, jclass jclazz){
    LOGI("Java_com_korion_lame_Mp3Encoder_destroy");
    if (encoder != NULL) {
        encoder->Destroy();
    }
}

#ifdef __cplusplus
}
#endif